package com.tg.client.hystrix;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheKey;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheRemove;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult;
import com.tg.contract.dto.RibbonMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * Created by linzc on 2019/3/7.
 */
@Service
public class CustomerService {

    @Autowired
    private RestTemplate restTemplate;

    @CacheResult(cacheKeyMethod = "getKey")
    @HystrixCommand(
            fallbackMethod = "goFallback",
            groupKey = "customerGroup",
            commandKey = "getCustomer", commandProperties = {
            //超时
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "200"),
            //开启请求缓存
            @HystrixProperty(name = "requestCache.enabled", value = "true"),
            //设置熔断
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
            //断路器的最小请求数
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "1"),
            //休眠时间
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "200"),
            //断路频率
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")
    })

    public String getCustomer(@CacheKey("id") String id) {
        RibbonMessage msg = restTemplate.getForObject("http://TG-RIBBON-SERVICE/ribbonAccept?id=" + id, RibbonMessage.class);
        System.out.println(msg);
        return msg.toString();
    }

    /**
     * 注意，@CacheRemove必须配合@HystrixCommand使用才有效果
     * @param id
     * @return
     */
    @HystrixCommand
    @CacheRemove(commandKey = "getCustomer", cacheKeyMethod = "getKey")
    public String clearCache(@CacheKey("id") String id) {
        return id;
    }

    public String getKey(String id) {
        return id;
    }

    public String goFallback(String id) {
        return "error:" + id;
    }

}
